package com.yimi.yinhepda.utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;

import com.liji.imagezoom.util.ImageZoom;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SharedPreferUtil;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.check_balance.GlideSimpleAdapter;
import com.pda.uce.commom.util.MyDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by msa1111 on 2018/6/6.
 */

public class SelectPicView extends RelativeLayout {

    /**
     * 图片展示器
     */
    private GridView mGridView;
    /**
     * 图片选择器
     */
    private GalleryConfig galleryConfig;
    /**
     * 选择图片路径
     */
    private List<String> pickPic = new ArrayList<>();
    /**
     * 图片展示器
     */
    private GlideSimpleAdapter simpleAdapter;
    /**
     * 存储图片集合
     */
    private List<HashMap<String, Object>> dataList = new ArrayList<>();
    private SharedPreferUtil sharedPreferUtil = SharedPreferUtil.getInstance();

    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 101;

    private static final int PICURE_NUM = 4;
    boolean isGalleryConfigPick = false;

    public SelectPicView(final Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.view_select_pic, this);
        mGridView = (GridView) findViewById(R.id.check_balance_gv_pic);

        simpleAdapter =
                new GlideSimpleAdapter(context, dataList, R.layout.gridview_item1, new String[]{"itemImage"}, new int[]{R.id.imageView2}, pickPic);
        mGridView.setAdapter(simpleAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //图片展示
                ImageZoom.show(context, position, pickPic);
            }
        });
        mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//                TipHelper.Vibrate(CheckBalanceActivity.this, 500);
                MyDialog deleteDialog = new MyDialog(context);
                deleteDialog.setIcon(R.drawable.alert);
                deleteDialog.setMessage("确定删除该图片吗?");
                deleteDialog.setPositiveClickListener( "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        dataList.remove(position);
                        pickPic.remove(position);
                        List<String> tempPickPic = new ArrayList<>();
                        tempPickPic.addAll(pickPic);
                        resetPicture(tempPickPic);
                    }
                });
                deleteDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "取消", null);
                deleteDialog.show();

                return true;
            }
        });


        //初始化图片选择框架
        galleryConfig = new GalleryConfig.Builder()
                // 监听接口（必填）
                .iHandlerCallBack(iHandlerCallBack)
                // provider (必填)
                .imageLoader(new GlideImageLoader()).provider("com.yimi.yinhepda.fileprovider")
                // 记录已选的图片
                .pathList(pickPic)
                // 配置是否多选的同时 配置多选数量   默认：false
                .multiSelect(true, PICURE_NUM)
                // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false)
                //设置水印
                .setWaterMask(true)
                //设置水印文字
                .setWaterMaskText(sharedPreferUtil.getEmpName() + " " + sharedPreferUtil.getWorkNum() + " 解")
                // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .crop(false, 1, 1, 500, 500)
                // 是否实现相机按钮  默认：false
                .isShowCamera(true)
                // 图片存放路径
                .filePath("/Gallery/Pictures").build();
    }

    public SelectPicView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    private void resetPicture(List<String> photoList) {

        pickPic.clear();
        dataList.clear();

        if (photoList != null && photoList.size() > 0) {
            pickPic.addAll(photoList);
        }

        if (photoList != null) {
            for (int i = 0; i < photoList.size(); i++) {
                HashMap<String, Object> gridviewItem = new HashMap<>();
                gridviewItem.put("itemImage", photoList.get(i));
                dataList.add(gridviewItem);
            }
        }

        simpleAdapter.notifyDataSetChanged();

        if (!isGalleryConfigPick) {
            galleryConfig.getBuilder().pathList(pickPic);
        }
        isGalleryConfigPick = false;
    }

    /**
     * 图片加载框架，返回图接口
     */
    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
            LogUtil.e("onStart: 开启");
        }

        @Override
        public void onSuccess(List<String> photoList) {
            LogUtil.e("onSuccess: 返回数据");
            for (String s : photoList) {
                LogUtil.e(s);
            }
            resetPicture(photoList);
        }

        @Override
        public void onCancel() {
            LogUtil.e("onCancel: 取消");
        }

        @Override
        public void onFinish() {
            LogUtil.e("onFinish: 结束");
        }

        @Override
        public void onError() {
            LogUtil.e("onError: 出错");
        }
    };

    /**
     * 拍照选择图片功能
     */
    public void takePhotoFunction(Activity activity) {
        galleryConfig.getBuilder().pathList(pickPic);
        galleryConfig.getBuilder().isOpenCamera(false).build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(activity);
    }

    /**
     * 打开相机拍照功能
     */
    public void openPhotoFunction(Activity activity){
        galleryConfig.getBuilder().isOpenCamera(true).build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(activity);
    }



    public List<String> getPickPic() {
        return pickPic;
    }

    public void setPickPic(List<String> pickPic) {
        this.pickPic = pickPic;
    }

    public void setClearPic() {
        pickPic.clear();
        dataList.clear();
        simpleAdapter.notifyDataSetChanged();
    }

}
